package com.x.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * the class of advance
 *
 * 提供文件下载接口
 * <p>
 * .
 *
 * @author little_lunatic
 * @date 2024-06-04
 */
@RestController
@Slf4j
@RequestMapping("/download")
public class DownloadController {

    @RequestMapping("/a")
    public void download(HttpServletResponse response) {

        String basePath = "D:\\Desktop\\";
        String filename = "pam-agent.zip";
        String filePath = basePath + filename;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 读取文件
            File file = new File(filePath);
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        }catch (Exception e) {
            log.error("文件下载异常", e);
        }
    }
}
